package main

import (
	"fmt"
	"github.com/gdamore/tcell"
	"os"
	"strconv"
)

func emitStr(s tcell.Screen, x, y int, style tcell.Style, str string) {
	for _, c := range str {
		s.SetCell(x, y, style, c)
		x++
	}
}

func main() {
	//encoding.Register()

	s, e := tcell.NewScreen()
	if e != nil {
		fmt.Fprintf(os.Stderr, "%v\n", e)
		os.Exit(1)
	}
	if e := s.Init(); e != nil {
		fmt.Fprintf(os.Stderr, "%v\n", e)
		os.Exit(1)
	}
	defStyle := tcell.StyleDefault.
		Background(tcell.ColorBlack).
		Foreground(tcell.ColorWhite)
	s.SetStyle(defStyle)
	s.EnableMouse()
	s.Clear()
	posFmt := "Mouse: %d, %d  "
	btnFmt := "Buttons: %s"
	keyFmt := "Keys: %s"
	white := tcell.StyleDefault.
		Foreground(tcell.ColorWhite).Background(tcell.ColorRed)
	mx, my := -1, -1
	w, h := s.Size()
	bStr := ""
	lks := ""
	eCnt := 0

	for {
		emitStr(s, 2, 2, white, "Press ESC twice to exit, C to clear.")
		emitStr(s, 2, 3, white, fmt.Sprintf(posFmt, mx, my))
		emitStr(s, 2, 4, white, fmt.Sprintf(btnFmt, bStr))
		emitStr(s, 2, 5, white, fmt.Sprintf(keyFmt, lks))

		s.Show()
		bStr = ""
		ev := s.PollEvent()
		st := tcell.StyleDefault.Background(tcell.ColorRed)
		w, h = s.Size()
		switch ev := ev.(type) {
		case *tcell.EventResize:
			s.Sync()
			s.SetCell(w-1, h-1, st, 'R')
		case *tcell.EventKey:
			s.SetCell(w-2, h-2, st, ev.Rune())
			s.SetCell(w-1, h-1, st, 'K')
			if ev.Key() == tcell.KeyEscape {
				eCnt++
				if eCnt > 1 {
					s.Fini()
					os.Exit(0)
				}
			} else {
				eCnt = 0
				if ev.Rune() == 'C' || ev.Rune() == 'c' {
					s.Clear()
				}
			}
			lks = ev.Name()
		case *tcell.EventMouse:
			x, y := ev.Position()  // 获取鼠标位置
			button := ev.Buttons() // 获取鼠标按键是哪个  1-鼠标左键 2-鼠标中键 256-滚轮上滚 512-滚轮下滚
			bStr = strconv.Itoa(int(button)) + " - "
			for i := uint(0); i < 8; i++ {
				if int(button)&(1<<i) != 0 {
					bStr += fmt.Sprintf(" Button%d", i+1)
				}
			}
			if button&tcell.WheelUp != 0 {
				bStr += " WheelUp"
			}
			if button&tcell.WheelDown != 0 {
				bStr += " WheelDown"
			}
			if button&tcell.WheelLeft != 0 {
				bStr += " WheelLeft"
			}
			if button&tcell.WheelRight != 0 {
				bStr += " WheelRight"
			}
			// Only buttons, not wheel events
			button &= tcell.ButtonMask(0xff)
			s.SetCell(w-1, h-1, st, 'M')
			mx, my = x, y
		default:
			s.SetCell(w-1, h-1, st, 'X')
		}
	}
}
